package com.atguigu.tingshu.search.listener;

import com.atguigu.tingshu.search.service.impl.ItemServiceImpl;
import org.redisson.api.RBloomFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.util.List;

public class DistroBloomFilterInitListener implements SpringApplicationRunListener {

    Logger logger = LoggerFactory.getLogger(DistroBloomFilterInitListener.class);

    /**
     * 在spring刷新完毕springboot启动过程中回来回调该方法。
     * ConfigurableApplicationContext：spring容器（应用的Bean对象）
     * started（）会被springboot回调两次
     * 1）springboot加载cloud组件比如nacos. 此时传入来的容器是没有应用的Bean对象，只拥有默认的Bean对象
     * 2）springboot自己启动的过程中来回调， ConfigurableApplicationContext容器才拥有应用的Bean对象
     *
     * @param context   the application context.
     * @param timeTaken the time taken to start the application or {@code null} if unknown
     */
    @Override
    public void started(ConfigurableApplicationContext context, Duration timeTaken) {

        // 初始化布隆过滤器
        boolean containsBean = context.containsBean("rBloomFilter");
        if (containsBean) {
            // 1.获取布隆过滤器对象
            RBloomFilter rBloomFilter = context.getBean("rBloomFilter", RBloomFilter.class);
            long count = rBloomFilter.count();
            if (count == 0) {
                // 2.获取数据
                ItemServiceImpl itemServiceImpl = context.getBean("itemServiceImpl", ItemServiceImpl.class);
                List<Long> albumIds = itemServiceImpl.getAlbumIds();
                // 3.将数据放到布隆过滤器中
                if (!CollectionUtils.isEmpty(albumIds)) {
                    for (Long albumId : albumIds) {
                        rBloomFilter.add(albumId);
                    }
                    logger.info("分布式布隆过滤器数据初始化完毕，且元素个数为：{}", rBloomFilter.count());
                }
            }

        }


    }


}